<template>
	<view class="event">
		<view class="date-picker">
			<picker mode="date" :value="date" :start="startDate" :end="endDate" @change="bindDateChange">
				<view style="text-align: center;">{{ date }}</view>
			</picker>
		</view>
		<timetable :timetables="timetables" :key="tableKey" ></timetable>
		<uni-fab horizontal="right" icon="add" @fabClick="addEvent" style="opacity: 0.5;"></uni-fab>
	</view>
</template>

<script>
import Timetable from '@/components/lpx-timetable/lpx-timetable'
export default {
	data() {
		return {
			title: 'Event',
			timetables: [],
			date: this.getDate(),
			tableKey: new Date().getTime()
		}
	},
	computed: {
		startDate() {
			return this.getDate('start');
		},
		endDate() {
			return this.getDate('end');
		}
	},
	components: {
		Timetable
	},
	async onShow() {
		await this.getEventList()
	},
	methods: {
		group(array, subGroupLength) {
			let index = 0;
			let newArray = [];
			while (index < array.length) {
				newArray.push(array.slice(index, index += subGroupLength));
			}
			return newArray;
		},
		resetTable() {
			this.timetables = []
			this.tableKey = new Date().getTime()
			for (let i = 0; i < 4; i++) {
				let timetable = []
				for (let j = 0; j < 12; j++) {
					timetable.push(null)
				}
				this.timetables.push(timetable)
			}
		},
		async getEventList() {
			let result = await this.$API.event.getEventList({ eventDate: this.date })
			this.resetTable()
			if (result.code === 200) {
				let newList = []
				for (let i = 0; i < 48; i++) {
					newList.push(null)
				}
				result.data.forEach(item => {
					let start = item.eventStart.slice(11, 16)
					let end = item.eventEnd.slice(11, 16)
					let startHour = parseInt(start.split(':')[0])
					let startMinute = parseInt(start.split(':')[1])
					let endHour = parseInt(end.split(':')[0])
					let endMinute = parseInt(end.split(':')[1])
					let startRow = startHour * 2 + startMinute / 30
					let endRow = endHour * 2 + (endMinute+1) / 30
					for (let i = startRow; i < endRow; i++) {
						newList[i] = item
					}
				})
				this.timetables = this.group(newList, 12)
			}	
		},
		getDate(type) {
			const date = new Date();
			let year = date.getFullYear();
			let month = date.getMonth() + 1;
			let day = date.getDate();

			if (type === 'start') {
				year = year - 60;
			} else if (type === 'end') {
				year = year + 2;
			}
			month = month > 9 ? month : '0' + month;
			day = day > 9 ? day : '0' + day;
			return `${year}-${month}-${day}`;
		},
		bindDateChange: async function (e) {
			this.date = e.detail.value
			await this.getEventList()
		},
		addEvent() {
			uni.setStorageSync('eventDate', this.date);
			uni.navigateTo({
				url: '/pages/event/add/index'
			})
		}
	}
}
</script>

<style scoped lang="scss">
.event {
	display: flex;
	flex-direction: column;
	width: 100%;
	height: 100%;
}

.date-picker {
	display: flex;
	justify-content: center;
	align-items: center;
	padding: 6rpx 0;
}
</style>
